<template>
  <div class="excel-container">
    <upload-excel :before-upload="beforeUpload" :on-success="onSuccess" />
  </div>
</template>

<script>
import UploadExcel from '@/components/UploadExcel'
import { batchEmployee } from '@/api/employee'
export default {
  name: 'ImportExcel',
  components: { UploadExcel },
  methods: {
    beforeUpload(file) {
      console.log(file)
      const isLt1M = file.size / 1024 / 1024 < 1
      if (!isLt1M) {
        this.$message.error('文件大小不能大于1M')
      }
      console.log(isLt1M)
      return isLt1M
    },
    async onSuccess({ header, results }) {
      // console.log(header)
      // console.log(results)
      // 中英文对照关系
      const headerRelation = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment',
        '部门': 'departmentName'
      }
      console.log(this.transData(results, headerRelation))
      await batchEmployee(this.transData(results, headerRelation))
      this.$message.success('批量导入员工成功')
    },
    transData(arr, relation) {
      const newArr = []
      arr.forEach(item => {
        const obj = {}
        for (const key in item) {
          obj[relation[key]] = item[key]
        }
        newArr.push(obj)
      })
      return newArr
    }
  }
}
</script>

<style lang="scss" scoped>
.excel-container{
  padding: 50px;
}
</style>
